package com.uduemc.security.core.controller;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.uduemc.security.core.SecurityProperties;
import com.uduemc.security.core.component.ImageCodeAndBufferedImage;
import com.uduemc.security.core.component.ValidateCodeImage;

@Controller
public class ValidateController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";

	// session 工具类
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

	@Autowired
	private SecurityProperties securityProperties;

	@GetMapping("/image/code")
	public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

		WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(request.getServletContext());

		ValidateCodeImage validateCodeImage = requiredWebApplicationContext
				.getBean(securityProperties.getValidate().getAchieveName(), ValidateCodeImage.class);

		// 第一步：请求生成一个图形验证码对象
		ImageCodeAndBufferedImage imageCodeAndBufferedImage = validateCodeImage.createImageCode(request);
		// 第二步：将图形验证码对象存到session中，8k
		// 第一个参数可以从传入的请求中获取session
		// 或者使用 new ServletWebRequest(request)
		// 其实这两个都是工具类，对传入的 request 进行封装然后操作session
		sessionStrategy.setAttribute(new ServletRequestAttributes(request), SESSION_KEY,
				imageCodeAndBufferedImage.getImageCode());
		// 第三步：将生成的图片写到接口的响应中
		ImageIO.write(imageCodeAndBufferedImage.getBufferedImage(), "JPEG", response.getOutputStream());
	}

	@GetMapping("/sms/code")
	@ResponseBody
	public String smsCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletRequestBindingException {
		WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(request.getServletContext());

		ValidateCodeImage validateCodeImage = requiredWebApplicationContext
				.getBean(securityProperties.getValidate().getAchieveName(), ValidateCodeImage.class);

		// 发送短信验证码的过程跟显示图片验证码的过程类似，前两部一样，最后一步是一个发送短信的服务，这里模拟实现
		ImageCodeAndBufferedImage imageCodeAndBufferedImage = validateCodeImage.createImageCode(request);
		sessionStrategy.setAttribute(new ServletRequestAttributes(request), SESSION_KEY,
				imageCodeAndBufferedImage.getImageCode());
		
		Long mobile = null;
		try {
			mobile = ServletRequestUtils.getLongParameter(request, "mobile");
			if(null == mobile || mobile < 10000000000L) {
				throw new ServletRequestBindingException("手机号码不能为空");
			}
		} catch (ServletRequestBindingException e) {
			return "手机号码不能为空";
		}
		// 发送短信服务
		logger.info("模拟发送短信验证码：" + imageCodeAndBufferedImage.getImageCode().getCode() + " 至手机号："
				+ mobile);
		return "SUCCESS";
	}

}
